<template>
  <Dialog v-model="dialogVisible" title="修改">
    <el-form
      ref="formRef"
      v-loading="formLoading"
      :model="formData.value"
      :rules="formRules"
      label-width="100px"
    >
      <el-row>
        <el-col :span="16">
          <el-form-item label="标题" prop="title">
            <el-input v-model="formData.value.title" placeholder="标题" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="有效" prop="status">
            <el-switch
              v-model="formData.value.status"
              placeholder="是否有效"
              :active-value="0"
              :inactive-value="1"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="链接" prop="url">
        <el-input v-model="formData.value.url" placeholder="跳转链接" />
      </el-form-item>
      <el-form-item label="小程序appid" prop="appid">
        <el-input v-model="formData.value.appId" disabled placeholder="小程序appid" />
      </el-form-item>
      <el-form-item label="小程序路径" prop="pagePath">
        <el-input v-model="formData.value.appPath" placeholder="小程序pagePath" />
      </el-form-item>
      <el-form-item label="模版名称" prop="templateId">
        <el-input v-model="formData.value.templateId" placeholder="模版名称" />
      </el-form-item>
      <div class="message-fill">
        <el-form-item class="form-group-title">消息填充数据，请对照模板内容填写</el-form-item>
        <el-form-item>
          <el-input
            type="textarea"
            disabled
            autosize
            v-model="formData.value.content"
            placeholder="模版"
          />
        </el-form-item>
        <el-row v-for="(item, index) in formData.value.messageData" :key="item.templateId">
          <el-col :span="16">
            <el-form-item :label="item.name" :prop="'data.' + index + '.value'">
              <el-input
                type="textarea"
                autosize
                rows="1"
                v-model="item.value"
                placeholder="填充内容"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="颜色">
              <el-input type="color" v-model="item.color" placeholder="颜色" />
            </el-form-item>
          </el-col>
        </el-row>
      </div>
    </el-form>
    <template #footer>
      <el-button :disabled="formLoading" type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script lang="ts" setup>
import * as MpTemplateApi from '@/api/mp/template'

defineOptions({ name: 'MpUserForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const formLoading = ref(false) // 表单的加载中
const formData = reactive({
  id: undefined,
  templateId: '',
  title: '',
  messageData: [],
  url: '',
  appId: '',
  appPath: '',
  content: '',
  status: true
})
// 表单的校验
const formRules = reactive({
  title: [{ required: true, message: '模板标题不能为空', trigger: 'blur' }],
  messageData: [{ required: true, message: '模板内容不能为空', trigger: 'blur' }],
  templateId: [{ required: true, message: '模板名称不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (id: number) => {
  dialogVisible.value = true
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      const response = await MpTemplateApi.getTemplate(id)
      formattingTemplate(response)
    } finally {
      formLoading.value = false
    }
  }
}
const formattingTemplate = (data) => {
  // 字段存在
  if (data.messageData instanceof Array) {
    formData.value = data
  } else {
    // 字段不存在，需要格式化
    data.messageData = []
    //示例： ["{{first.DATA}}", "{{keyword1.DATA}}", "{{keyword2.DATA}}", "{{remark.DATA}}"]
    let keysArray = data.content.match(/\{\{(\w*)\.DATA\}\}/g) || []
    keysArray.map((item) => {
      // 匹配出.DATA前面
      let name = item.replace('{{', '').replace('.DATA}}', '')
      data.messageData.push({
        name: name,
        value: '',
        color: '#000000'
      })
      formData.value = data
    })
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  try {
    await MpTemplateApi.updateTemplate(formData.value)
    message.success(t('common.updateSuccess'))
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    nickname: undefined,
    remark: undefined,
    tagIds: []
  }
  formRef.value?.resetFields()
}
</script>
<style scoped>
.message-fill {
  border: 1px dotted gray;
  padding: 10px;
}
</style>
